package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.UserNotLoginException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WeChatProperties weChatProperties;
    public static final String URL="https://api.weixin.qq.com/sns/jscode2session";
    @Override
    public User login(UserLoginDTO userLoginDTO) {

       String code = userLoginDTO.getCode();
        String openid = getOpenId(code);
//        判断openid是否为空(如果授权码错误，那么微信的接口服务返回的openid就是空的)
        if(openid==null){
            throw new UserNotLoginException(MessageConstant.LOGIN_FAILED);
        }
//        如果微信用户合法，则判断是否为新用户
        User user=userMapper.selectUser(openid);
        // 如果为新用户，则自动注册（注意这里要返回主键id，因为Controller层需要返回用户的主键id给前端）
        if(user==null){
            user = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.save(user);
        }

//        返回用户对象

        return user;
    }

    public String getOpenId(String code){
        HashMap<String, String> ParamMap = new HashMap<>();
        ParamMap.put("appid", weChatProperties.getAppid());
        ParamMap.put("secret",weChatProperties.getSecret());
        ParamMap.put("js_code",code);
        ParamMap.put("grant_type","authorization_code");
        //       利用httpclient请求 auth.code2Session接口获取openid
        String jsonObject = HttpClientUtil.doGet(URL, ParamMap);
        JSONObject jsonUser = JSON.parseObject(jsonObject);
        String openid = jsonUser.getString("openid");
        log.info("微信用户的openid为:{}",openid);
        return openid;
    }
}
